package com.example.springboot.service;

import com.example.springboot.dto.CommentDTO;
import com.example.springboot.entity.ForumComment;
import com.example.springboot.mapper.ForumCommentMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class ForumCommentService {

    @Autowired
    private ForumCommentMapper forumCommentMapper;

    private static final Logger logger = LoggerFactory.getLogger(ForumCommentService.class);

    public void createComment(ForumComment comment) {
        forumCommentMapper.insertComment(comment);
    }

    public CommentDTO getCommentById(Integer commentId) {
        return forumCommentMapper.getCommentWithUserInfo(commentId);
    }

    public List<ForumComment> getCommentsByPostId(Integer postId) {
        return forumCommentMapper.selectCommentsByPostId(postId);
    }

    public void updateComment(ForumComment comment) {
        forumCommentMapper.updateComment(comment);
    }

    public void deleteComment(Integer commentId) {
        forumCommentMapper.deleteComment(commentId);
    }

    public List<ForumComment> getCommentsByUserId(Integer userId) {
        return forumCommentMapper.selectCommentsByUserId(userId);
    }

    public Page<ForumComment> getAllCommentsForAdmin(String username, int page, int size, String query) {
        if (!hasSuperRole(username)) {
            logger.warn("User {} has no super admin privileges", username);
            return null;
        }
        PageHelper.startPage(page, size, "created_at DESC");
        if (query != null && !query.trim().isEmpty()) {
            return forumCommentMapper.findByQuery(query);
        }
        return forumCommentMapper.findAllComments();
    }

    public boolean deleteCommentAdmin(Integer commentId, String username) {
        if (!hasSuperRole(username)) {
            logger.warn("User {} has no super admin privileges", username);
            return false;
        }
        forumCommentMapper.delete(commentId);
        return true;
    }

    private boolean hasSuperRole(String username) {
        if (username == null) {
            return false;
        }
        String role = forumCommentMapper.findRoleByUsername(username);
        return "super".equals(role);
    }
}